package com.sychip.fhc.app.data.source.dao


import androidx.room.Dao
import androidx.room.Query
import androidx.room.Upsert
import com.sychip.fhc.app.data.source.entity.WsnRssiHisEntity
import timber.log.Timber

const val TBL_WsnRssiHis = "wsnRssiHis"
@Dao
interface WsnRssiHisDao {

    /**
     * Select all tasks from the tasks table.
     *
     * @return all tasks.
     */
    @Query("SELECT * FROM $TBL_WsnRssiHis WHERE usbId = :usbId")
    suspend fun getAll(usbId: String): List<WsnRssiHisEntity>


    @androidx.room.RawQuery
    suspend fun getAllParseLikeWithParts(usbId: String, rssiType: Int, parts: List<String>): List<String> {
        val query = buildString {
            append("SELECT distinct rssiParse FROM $TBL_WsnRssiHis WHERE usbId = '$usbId' AND rssiType = $rssiType")
            if (parts.isNotEmpty()) {
                append(" AND (")
                parts.forEachIndexed { index, part ->
                    if (index > 0) append(" OR ")
                    append("rssiParse LIKE '%$part%'")
                }
                append(")")
            }
        }
        Timber.i("getAllParseLikeWithParts:  %s", query)
        val list = getAllParseLikeWithParts(androidx.sqlite.db.SimpleSQLiteQuery(query))
        // 注意：这种方法存在 SQL 注入风险，实际使用中应使用参数化查询
        return getAllParseLikeWithParts(androidx.sqlite.db.SimpleSQLiteQuery(query))
    }

    @androidx.room.RawQuery
    suspend fun getAllParseLikeWithParts(supportSQLiteQuery: androidx.sqlite.db.SupportSQLiteQuery): List<String>


    /**
     * Insert or update a bleDevice in the database. If a bleDevice already exists, replace it.
     *
     * @param bleDevice the bleDevice to be inserted or updated.
     */
    @Upsert
    suspend fun upsert(bleDevice: WsnRssiHisEntity)


    /**
     * Delete a bleDevice by id.
     *
     * @return the number of tasks deleted. This should always be 1.
     */
    @Query("DELETE FROM $TBL_WsnRssiHis WHERE dateTime = :fromTime")
    suspend fun deleteByFromTime(fromTime: Long): Int

    /**
     * Delete all tasks.
     */
    @Query("DELETE FROM $TBL_WsnRssiHis WHERE usbId = :usbId")
    suspend fun deleteAll(usbId: String): Int

}
